using System;
using Newtonsoft.Json;
using BanZuiCloudControlAgent.Core.Tasks.Enums;

namespace BanZuiCloudControlAgent.Core.Tasks.Models
{
    /// <summary>
    /// 任务状态信息，用于状态上报中包含任务状态
    /// </summary>
    public class TaskStatusInfo
    {
        /// <summary>
        /// 任务ID
        /// </summary>
        [JsonProperty("taskId")]
        public string TaskId { get; set; }
        
        /// <summary>
        /// 任务类型
        /// </summary>
        [JsonProperty("taskType")]
        public string TaskType { get; set; }
        
        /// <summary>
        /// 任务状态
        /// </summary>
        [JsonProperty("status")]
        public string Status { get; set; }
        
        /// <summary>
        /// 任务进度（0-100）
        /// </summary>
        [JsonProperty("progress")]
        public int Progress { get; set; }
        
        /// <summary>
        /// 任务开始时间
        /// </summary>
        [JsonProperty("startTime")]
        public DateTime? StartTime { get; set; }
        
        /// <summary>
        /// 任务运行时长（秒）
        /// </summary>
        [JsonProperty("runningTime")]
        public int RunningTime { get; set; }
        
        /// <summary>
        /// 从BaseTask创建TaskStatusInfo
        /// </summary>
        /// <param name="task">任务</param>
        /// <returns>任务状态信息</returns>
        public static TaskStatusInfo FromTask(Base.BaseTask task)
        {
            if (task == null)
            {
                return null;
            }
            
            var info = new TaskStatusInfo
            {
                TaskId = task.TaskId,
                TaskType = task.TaskType.ToString(),
                Status = task.Status.ToString(),
                Progress = task.Progress,
                StartTime = task.StartTime
            };
            
            // 计算运行时长
            if (task.StartTime.HasValue && task.Status == TaskState.Running)
            {
                var runningTime = DateTime.Now - task.StartTime.Value;
                info.RunningTime = (int)runningTime.TotalSeconds;
            }
            else if (task.StartTime.HasValue && task.CompleteTime.HasValue)
            {
                var runningTime = task.CompleteTime.Value - task.StartTime.Value;
                info.RunningTime = (int)runningTime.TotalSeconds;
            }
            else
            {
                info.RunningTime = 0;
            }
            
            return info;
        }
    }
} 